package com.yl.chainStore.control

import cn.hutool.core.collection.ListUtil
import cn.hutool.core.map.MapUtil
import com.alibaba.fastjson.JSONArray
import com.alibaba.fastjson.JSONObject
import com.yl.chainStore.services.IdbImportService
import com.yl.common.ErrorCode
import com.yl.common.UserType
import com.yl.common.control.ResponseBody
import com.yl.common.control.returnError
import com.yl.common.control.returnSuccess
import com.yl.common.getContext
import com.yl.message.vo.ToUserMessageVo
import com.yl.users.common.enum.UserPackageTypeEnum
import com.yl.users.entity.CompanyDept
import com.yl.users.entity.CompanyRole
import com.yl.users.entity.CompanyUser
import com.yl.users.pojo.vo.CompanyRoleSelectVo
import com.yl.users.services.ICompanyDeptService
import com.yl.users.services.ICompanyUserService
import com.yl.users.services.ISysCompanyService
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.transaction.annotation.TransactionAnnotationParser
import org.springframework.transaction.annotation.Transactional
import org.springframework.transaction.interceptor.TransactionAspectSupport
import org.springframework.web.bind.annotation.PostMapping
import org.springframework.web.bind.annotation.RequestBody
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RestController
import java.util.*
import kotlin.collections.ArrayList

@RestController
@RequestMapping("sys/import")
open class ImportDbController (
	private val iSysCompanyService: ISysCompanyService,
	private val iCompanyUserService: ICompanyUserService,
	private val iCompanyDeptService: ICompanyDeptService,
	private val idbImportService: IdbImportService,
		):BaseCtrl(){


	@RequestMapping("importCompanyUser")
	@Transactional(rollbackFor = [Exception::class])
	open fun importCompanyUser(@RequestBody array:JSONArray):ResponseBody{

		//以后暂时不用了
		val a = 1
		if(a == 1){
			return returnSuccess()
		}
		val userList = mutableListOf<CompanyUser>()
		val roleList = iSysCompanyService.getCompanyRoleList(CompanyRoleSelectVo())
		val subCompanyList = iSysCompanyService.getSubCompanyList(getContext().companyId)

		for(userJson in array){
			val map = userJson as Map<String,Any?>
			val name = map["name"]
			val nameCode = map["nameCode"]
			val birth = map["birth"]
			val sex = map["sex"]
			val job = map["job"]
			val title = map["title"]
			val email = map["email"]
			val mobile = map["mobile"]
			val homeAddress = map["homeAddress"]
			val show = map["show"]
			val departmentId = map["departmentId"]
			val department = map["department"]
			val userID = map["userID"]
			val user = map["user"]  //对象
			val employeeNo = map["employeeNo"]
			val relatedProviderId = map["relatedProviderId"]
			val workingOffices = map["workingOffices"] as List<Map<String,Any?>>// 数组
			val showOrder = map["showOrder"]
			val isUserEdited = map["isUserEdited"]
			val certificateNo = map["userID"]
			val isIntern = map["userID"]
			val isMobileVerified = map["isMobileVerified"]
			val needSendMessage = map["needSendMessage"]
			val instructorId = map["instructorId"]
			val identityCard = map["identityCard"]
			val mobileAreaCode = map["mobileAreaCode"]
			val workingDepartments = map["workingDepartments"]
			val roleNames = map["roleNames"]
			val officeId = map["officeId"]
			val id = map["id"]







			val companyUser = CompanyUser(
				id= 0,
//				loginName = account?.toString(),
				realName = name!!.toString(),
				phone = mobile?.toString(),
				createTime = Date(),
				updateTime = Date(),
				userType = UserType.Company,
				userWorkType = UserPackageTypeEnum.getEnumByName(job.toString())
			)
			//user
			var roles:Any ? = null
			if(user != null){
				user as Map<String,Any>
				val account = user["account"]
				val isRoot = user["isRoot"]
				 roles = user["roles"]
				if(isRoot != null){
					isRoot as Boolean
					if(isRoot){
						companyUser.userCode = "admin"
					}
				}
				companyUser.loginName = account?.toString()
			}


			if(sex != null){
				sex as Int
				if(sex == 1){
					companyUser.gender = UserPackageTypeEnum.USER_GENDER_BOY
				}else if(sex == 2){
					companyUser.gender = UserPackageTypeEnum.USER_GENDER_GIRL
				}
			}

			val addUser = iSysCompanyService.addUser(companyUser)
			if(addUser.bodyIsError()){
				TransactionAspectSupport.currentTransactionStatus().setRollbackOnly()
				return addUser
			}

			val roleIds = mutableListOf<Long>()
			//roles
			if(roles != null){
				roles  	as List<Map<String,Any?>>
				for(role in roles){
					val roleName = role["name"] ?: continue
					var companyRole:CompanyRole ?= null
					for(sysRole in roleList){
						if(sysRole.roleName == roleName.toString()){
							companyRole = sysRole
							break
						}
					}
					if(companyRole == null){
						companyRole = CompanyRole(
							id = 0,
							roleName= roleName.toString(),
						)
						val addCompanyRole = iSysCompanyService.addCompanyRole(companyRole)
						if(addCompanyRole.bodyIsError()){
							TransactionAspectSupport.currentTransactionStatus().setRollbackOnly()
							return addCompanyRole
						}
						roleList.add(companyRole)
					}

					roleIds.add(companyRole.id)


					val roleIsTenantAdministrator = role["isTenantAdministrator"]
					val isDefault = role["isDefault"]
					val dataPermission = role["dataPermission"]
					val option = role["option"]
					val usingOfficeIds = role["usingOfficeIds"]
					val roleId = role["id"]
				}
			}

			//工作分院
			val subCompanyIds = mutableListOf<Long>()
			for(workOf in workingOffices){
				val workId = workOf["id"]
				val workName = workOf["name"]
				val code = workOf["code"]
				val abbreviation = workOf["abbreviation"]
				val address = workOf["address"]
				val phoneNumber = workOf["phoneNumber"]
				val pictureId = workOf["pictureId"]
				val point = workOf["point"]
				val parentId = workOf["parentId"]
				val officeType = workOf["officeType"]
				val bizType = workOf["bizType"]
				val expiredDate = workOf["expiredDate"]

				var companyDept:CompanyDept ?= null
				for(subDept in subCompanyList){
					if(workName.toString() == subDept.name){
						companyDept = subDept
						break
					}
				}
				if(companyDept == null){
					companyDept = CompanyDept(
						id = 0L,
						name = workName.toString(),
						phone = phoneNumber.toString(),
						address = address.toString(),
						subCompany = 1
					)
					val addSubCompany = iSysCompanyService.addSubCompany(companyDept)
					if(addSubCompany.bodyIsError()){
						TransactionAspectSupport.currentTransactionStatus().setRollbackOnly()
						return addSubCompany
					}
					subCompanyList.add(companyDept)
				}
				subCompanyIds.add(companyDept.id)

			}
			for(subId in subCompanyIds){
				val bindUserToDept = iCompanyDeptService.bindUserToDept(subId, companyUser.id)
				if(bindUserToDept.bodyIsError()){
					TransactionAspectSupport.currentTransactionStatus().setRollbackOnly()
					return bindUserToDept
				}
				val addRoles = iCompanyUserService.addRoles(companyUser.id, roleIds, subId)
				if(addRoles.bodyIsError()){
					TransactionAspectSupport.currentTransactionStatus().setRollbackOnly()
					return addRoles
				}
			}
		}

		return returnSuccess()
	}

	/**
	 * 导入患者信息
	 */
	@PostMapping("importCustomerInfo")
	@Transactional(rollbackFor = [Exception::class])
	open fun importCustomerInfo():ResponseBody{
		if(getContext().companyId == 0L){
			return returnError(ErrorCode.DATA_IS_NOT_FIND,"")
		}
//		return idbImportService.importCustomer()
		return returnError(ErrorCode.OPERATION_DATA_ERROR,"未启动代码")
	}

	/**
	 * 导入患者推荐情况
	 */
	@PostMapping("importCustomerSource")
	@Transactional(rollbackFor = [Exception::class])
	open fun importCustomerSource():ResponseBody{
		if(getContext().companyId == 0L){
			return returnError(ErrorCode.DATA_IS_NOT_FIND,"")
		}
//		return idbImportService.importCustomerSourceByCustomer()
		return returnError(ErrorCode.OPERATION_DATA_ERROR,"未启动代码")
	}

	/**
	 * 导入患者病历
	 */
	@PostMapping("importCustomerSickHistory")
	@Transactional(rollbackFor = [Exception::class])
	open fun importCustomerSickHistory():ResponseBody{
		if(getContext().companyId == 0L){
			return returnError(ErrorCode.DATA_IS_NOT_FIND,"")
		}
//		return idbImportService.importCustomerHistory()
		return returnError(ErrorCode.OPERATION_DATA_ERROR,"未启动代码")
	}

	/**
	 * 导入患者预约记录
	 */
	@PostMapping("importCustomerSubLog")
	@Transactional(rollbackFor = [Exception::class])
	open fun importCustomerSubLog():ResponseBody{
		if(getContext().companyId == 0L){
			return returnError(ErrorCode.DATA_IS_NOT_FIND,"")
		}
//		return idbImportService.importSubLog()
		return returnError(ErrorCode.OPERATION_DATA_ERROR,"未启动代码")
	}

	/**
	 * 导入患者就诊记录
	 */
	@PostMapping("importCustomerRecordDetail")
	@Transactional(rollbackFor = [Exception::class])
	open fun importCustomerRecordDetail():ResponseBody{
		if(getContext().companyId == 0L){
			return returnError(ErrorCode.DATA_IS_NOT_FIND,"")
		}
		return idbImportService.importCustomerRecordDetail()
//		return returnError(ErrorCode.OPERATION_DATA_ERROR,"未启动代码")
	}


	/**
	 * 导出
	 */
	@PostMapping("testUpLoad")
	open fun testUpliad(){
		val list = iCompanyUserService.getUserSubCompanyRoleIds(1, 1)
		val headAlias: MutableMap<String?, String?> = MapUtil.newHashMap(true)
		headAlias["title"] = "操作模块"
		headAlias["businessType"] = "业务类型"
		headAlias["method"] = "请求方法"
		headAlias["requestMethod"] = "请求方式"
		headAlias["operatorType"] = "操作类别"
		headAlias["operName"] = "操作人员"
		headAlias["deptName"] = "部门名称"
		headAlias["operUrl"] = "请求url"
		headAlias["operIp"] = "操作地址"
		headAlias["operLocation"] = "操作地点"
		headAlias["operParam"] = "请求参数"
		headAlias["jsonResult"] = "返回参数"
		headAlias["errorMsg"] = "错误消息"
		headAlias["operTime"] = "操作时间"
//		export(list, headAlias)
	}




}
